package com.gjintel.framework.util;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;

/**
 *  导入jacob.jar
 *  使用前将jacob-1.16-M1-x64.dll 和 jacob-1.16-M1-x86.dll 放入C:\Windows\System32下，
 *  将jacob-1.16-M1-x64.dll 放入C:\Windows\SysWOW64下
 *
 */

public class Word2Pdf {

    public static ActiveXComponent wordCom = null;

    public static  boolean saveWordAsPDF(String filePath, String outFile) {
        ComThread.InitSTA();
        wordCom = new ActiveXComponent("Word.Application");
        try {
            Dispatch wrdDocs = Dispatch.get(wordCom, "Documents").toDispatch();
            Dispatch wordDoc = Dispatch.call(wrdDocs, "Open", filePath,
                    new Variant( false), new Variant(false)).toDispatch();
            Dispatch.invoke(wordDoc, "ExportAsFixedFormat", Dispatch.Method, new Object[]{
                    outFile, new Variant(17), new Variant(false), new Variant(0), new Variant(0),
                    new Variant(0), new Variant(0), new Variant(false), new Variant(true),
                    new Variant(0), new Variant(false), new Variant(true), new Variant(false)}, new int[0]);
            return true;
        } catch (Exception es) {
            es.printStackTrace();
            return false;
        } finally {
            closeWord(false);
        }
    }

    public static void closeWord(boolean saveOnExit) {
        if (wordCom != null) {
            wordCom.invoke("Quit", new Variant(false));
            wordCom = null;
            ComThread.Release();
        }
    }



    /**
     * 调用
     * sourceFile原文件路径，outFile转化PDF文件路径
     * @param sourceFile
     * @param outFile
     * @return
     *
     */
    public static boolean  word2Pdf(String sourceFile,String outFile) {
        try{
            Word2Pdf.saveWordAsPDF(sourceFile, outFile);
            return true;
        }catch (Exception e){
            return false;
        }
    }

//    public static void main(String[] args){
//        try {
//            word2Pdf("C:\\1.doc","C:\\1.pdf");
//        }catch (Exception e){
//            System.out.println(e);
//        }
//
//    }

}
